package com.suep.system.core.filter;


import com.suep.system.utils.JWTUtil;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import com.suep.system.config.BaseR;

import java.io.PrintWriter;


@WebFilter
public class JWTFilter implements Filter {

    //注意：直接放行的接口将无法解析token,将部分属性放入request域里，当然，这里只是因为我懒得在JWT工具类加方法才有这个缺点

    // 定义不需要 token 验证的路径列表
    //这个之后通过yml自定义配置导入更加方便
    private static final String[] EXCLUDED_PATHS = {
            "/login", // 登录请求路径
            "/register", //
            "/email/sendEmail",
            "/file/load/"
    };
    // 检查请求的 URI 是否在不需要验证的路径列表中
    private boolean isExcludedPath(String requestURI) {
        for (String path : EXCLUDED_PATHS) {
            if (requestURI.startsWith(path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;


        // 获取请求的 URI
        String requestURI = httpRequest.getRequestURI();
        if (isExcludedPath(requestURI)) {
            // 如果是不需要验证的路径，直接放行请求
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String token = httpRequest.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            if(JWTUtil.validateToken(token)){
                Map<String,String> tokenInfo=JWTUtil.getUsernameAndRoleAndUserIdFromToken(token);
                String role=tokenInfo.get("role");
                String username=tokenInfo.get("username");
                String userId=tokenInfo.get("userId");

                httpRequest.setAttribute("username",username);
                httpRequest.setAttribute("role",role);
                httpRequest.setAttribute("userId",userId);
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }else {
            //返回401未认证响应码
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.setContentType("application/json;charset=UTF-8");

            // 创建 BaseR 对象
            BaseR<String> baseR = new BaseR<>(401, "请求没有携带有效令牌", null);

            // 将 BaseR 对象转换为 JSON 字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(baseR);

            // 通过响应输出流发送 JSON 数据
            try (PrintWriter out = httpResponse.getWriter()) {
                out.print(json);
                out.flush();
            }
        }
    }


}
